/*
** ssl_server.c
** 使用OpenSSL_1.1.1版本
*/
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

int create_socket(int port)
{
    int s;
    struct sockaddr_in addr;

    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);

    s = socket(AF_INET, SOCK_STREAM, 0);
    if (s < 0) {
		perror("Unable to create socket");
		exit(EXIT_FAILURE);
    }

    if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
		perror("Unable to bind");
		exit(EXIT_FAILURE);
    }

    if (listen(s, 1) < 0) {
		perror("Unable to listen");
		exit(EXIT_FAILURE);
    }

    return s;
}


int main(int argc, char **argv)
{
    int sock = -1;
    SSL_CTX *ctx = NULL;
	const char reply[1024*8] = {1, 2, 3, 4, 5, 6};
	
	//加载SSL算法和错误字符串
    SSL_load_error_strings();	
    OpenSSL_add_ssl_algorithms();
	
	//创建上下文(SSLv23_server_method)
    ctx = SSL_CTX_new(SSLv23_server_method());
    if (!ctx) {
		perror("Unable to create SSL context");
		ERR_print_errors_fp(stderr);
		exit(EXIT_FAILURE);
    }
	
	//设置自动秘钥交换，旧版本没有该函数
    SSL_CTX_set_ecdh_auto(ctx, 1);
	
    //设置Key和证书
    if (SSL_CTX_use_certificate_file(ctx, "client.crt", SSL_FILETYPE_PEM) <= 0) {
        ERR_print_errors_fp(stderr);
		exit(EXIT_FAILURE);
    }
	
	SSL_CTX_set_default_passwd_cb_userdata(ctx, (void*)"123456789"); //证书密码
	
    if (SSL_CTX_use_PrivateKey_file(ctx, "client.key", SSL_FILETYPE_PEM) <= 0 ) {
        ERR_print_errors_fp(stderr);
		exit(EXIT_FAILURE);
    }

	//创建socket，监听9999端口
    sock = create_socket(9999);

    /* Handle connections */
    while(1) {
        struct sockaddr_in addr;
        uint len = sizeof(addr);
        SSL *ssl;
        //返回客户端连接的socket
        int client = accept(sock, (struct sockaddr*)&addr, &len);
        if (client < 0) {
            perror("Unable to accept");
            exit(EXIT_FAILURE);
        }
		//将socket关联SSL
        ssl = SSL_new(ctx);
        SSL_set_fd(ssl, client);
		//进行TSL/SSL握手
        if (SSL_accept(ssl) <= 0) {
            ERR_print_errors_fp(stderr);
        }
        else {
			//发送数据
            SSL_write(ssl, reply, 1024*8);
        }

        SSL_shutdown(ssl);
        SSL_free(ssl);
        close(client);
    }

    close(sock);
    SSL_CTX_free(ctx);
    EVP_cleanup();
}